<script setup lang="ts">
import { reactive, computed, onMounted } from 'vue';
import { navigateTo, getCurrentInstance, showLoading, hideLoading } from '@tarojs/taro';
import {
  DELIVER_ORDER_STATUS,
  DELIVER_ORDER_STATUS_COLOR,
  DELIVER_ORDER_STATUS_BG_COLOR,
} from '/@/common/constant';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import {
  QUERY_APP_WO_DELIVER_DETAIL,
  EVALUATE_APP_TASK,
  RECEIVE_APP_TASK,
  BACK_APP_TASK,
  RUSH_APP_TASK,
  START_APP_TASK,
} from '/@/api/modules/deliver/app-wo-deliver';
import { formatSeconds } from '/@/utils/time';
import IMG_ICON_SPEED from '/@/assets/image/icon/speed.png';
import dayjs from 'dayjs';
import { ACCESS } from '/@/api/modules/qrcode/open';
import { SYS_REGION_LIST } from '/@/api/modules/base/sys-region';
import { scan } from '/@/utils/scan';
onMounted(() => {
  getDetail();
});

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  id: string;
  /**
   * default/report-history'
   *
   */
  from?: string;
};

const state = reactive<{
  /**
   * 工单信息
   */
  info: AppWoDeliver.Dto;
  endTaskEventItem?: AppWoDeliver.eventDto;
}>({
  info: {},
  endTaskEventItem: {},
});

/**
 * 工单评价表单
 */
const evaluateTaskFormState = reactive<{
  woDeliverEventDto: AppWoDeliver.eventDto;
  woDeliverDto: AppWoDeliver.Dto;
}>({
  woDeliverEventDto: {
    workOrderId: '',
    handleUserId: '',
    handleUserName: '',
    handleTime: undefined,
    opinion: '',
    starNumber: 0,
    starNumberQuality: 0,
  },
  woDeliverDto: {
    id: '',
  },
});

/**
 * 图片文件列表
 */
const imgList = computed(() => {
  if (!state.info.woDeliverFileDto || !state.info.woDeliverFileDto.length) return [];

  return [...(state.info.woDeliverFileDto as AppSysWorkOrder.FileDto[])]
    .filter((file) => {
      return file.fileType === 1;
    })
    .map((file) => {
      return {
        key: file.id || '',
        src: file.fileUrl || '',
      };
    });
});

/**
 * 图片文件列表
 */
const imgList4EndTaskEvent = computed(() => {
  if (
    !state.endTaskEventItem?.woDeliverEventFileDto ||
    !state.endTaskEventItem?.woDeliverEventFileDto.length
  )
    return [];

  return [...(state.endTaskEventItem.woDeliverEventFileDto as AppSysWorkOrder.FileDto[])]
    .filter((file) => {
      return file.fileType === 1;
    })
    .map((file) => {
      return {
        key: file.id || '',
        src: file.fileUrl || '',
      };
    });
});

/**
 * @function 获取工单详情
 */
function getDetail() {
  showLoading();
  QUERY_APP_WO_DELIVER_DETAIL({ id: params.id }).then((res) => {
    state.info = res.woDeliverDto;
    state.endTaskEventItem = state.info.woDeliverEventDto?.find((item) => {
      return item.eventCode === 'end_task';
    });
    const evaluateTaskEventIndex = state.info.woDeliverEventDto?.findIndex((item) => {
      return item.eventCode === 'evaluate_task';
    });

    if (evaluateTaskEventIndex && evaluateTaskEventIndex > 0) {
      evaluateTaskFormState.woDeliverEventDto.starNumber = (
        state.info.woDeliverEventDto as AppWoDeliver.eventDto[]
      )[evaluateTaskEventIndex].starNumber;
      evaluateTaskFormState.woDeliverEventDto.starNumberQuality = (
        state.info.woDeliverEventDto as AppWoDeliver.eventDto[]
      )[evaluateTaskEventIndex].starNumberQuality;
      evaluateTaskFormState.woDeliverEventDto.opinion = (
        state.info.woDeliverEventDto as AppWoDeliver.eventDto[]
      )[evaluateTaskEventIndex].opinion;
    }

    hideLoading();
  });
}

/**
 * @function 评价订单
 */
function evaluateTask() {
  LOGIN_APP().then((res) => {
    evaluateTaskFormState.woDeliverDto.id = params.id;
    evaluateTaskFormState.woDeliverEventDto.workOrderId = params.id;
    evaluateTaskFormState.woDeliverEventDto.handleUserId = res.sysUserDto.id;
    evaluateTaskFormState.woDeliverEventDto.handleUserName = res.sysUserDto.name;
    evaluateTaskFormState.woDeliverEventDto.handleTime = new Date().valueOf();

    EVALUATE_APP_TASK(evaluateTaskFormState).then(() => {
      getDetail();
    });
  });
}

/**
 * 抢单
 */
function rushAppTask() {
  showLoading();
  RUSH_APP_TASK({ woDeliverEventDto: { workOrderId: params.id } }).then(() => {
    getDetail();
  });
}

/**
 * 接单
 */
function receiveAppTask() {
  showLoading();
  RECEIVE_APP_TASK({ woDeliverEventDto: { workOrderId: params.id } }).then(() => {
    getDetail();
  });
}
/**
 * 回退
 */
function backAppTask() {
  showLoading();
  BACK_APP_TASK({ woDeliverEventDto: { workOrderId: params.id } }).then(() => {
    getDetail();
  });
}

/**
 * 开始运送工单-扫描
 */
function startAppTaskScan() {
  scan().then((res) => {
    scanResult(res);
  });
}

/**
 * 开始运送工单
 */
function startAppTask(areaId?: string, areaName?: string) {
  showLoading();
  START_APP_TASK({
    woDeliverEventDto: {
      workOrderId: params.id,
      qrcodeAreaId: areaId,
      qrcodeAreaName: areaName,
    },
  }).then(() => {
    navigateTo({
      url: `/pages/deliver/scan-success/index?id=${params.id}&status=task_start`,
    });
  });
}

/**
 * 计划时间
 */
const planTime = computed(() => {
  const planTimeStart = state.info.planTimeStart
    ? dayjs(state.info.planTimeStart).format('MM-DD HH:mm')
    : '-';
  const planTimeEnd = state.info.planTimeEnd
    ? dayjs(state.info.planTimeEnd).format('MM-DD HH:mm')
    : '-';
  return `${planTimeStart} 至 ${planTimeEnd}`;
});

/**
 * 扫描结果处理
 */
function scanResult(result: string) {
  console.log('scanResult===>', result);
  const url = new URL(result);
  const t = url.searchParams.get('t');
  if (!t) {
    navigateTo({
      url: `/pages/deliver/scan-fail/index?status=task_start&id=${params.id}`,
    });
    return;
  }
  ACCESS({ t: t }).then((res) => {
    if (!res.comResp || !res.content) {
      navigateTo({
        url: `/pages/deliver/scan-fail/index?status=task_start&id=${params.id}`,
      });
      return;
    }
    /**
     * 获取参数信息
     */
    const contentParams = res.content.params as {
      id: string;
    };
    switch (res.content?.businessTag) {
      case 'AREA_DETAIL':
        queryAreaDetail(contentParams.id);
        break;
      default:
        navigateTo({
          url: `/pages/deliver/scan-fail/index?status=task_start&id=${params.id}`,
        });
        break;
    }
  });
}

//根据id查询详情信息
function queryAreaDetail(areaId: string, page: number = 1, pageSize: number = 15) {
  showLoading();
  SYS_REGION_LIST({
    comQuery: { page, pageSize },
    id: areaId,
  }).then((res) => {
    if (!res.content || !res.content.length) return;
    //1.扫描的区域ID和工单开始地址ID相等
    //2.开始运送
    const areaId = res.content[0].id;
    const areaName = res.content[0].name;
    if (state.info.areaIdStart === areaId) {
      startAppTask(areaId, areaName);
    } else {
      navigateTo({
        url: `/pages/deliver/scan-fail/index?status=task_start&id=${params.id}`,
      });
    }
  });
}
</script>

<template>
  <view class="deliver-detail app-page--1">
    <app-navbar title="工单详情" />
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="deliver-detail__wrapper">
        <nut-cell-group>
          <nut-cell>
            <template v-slot:title>
              <view class="deliver-detail__module-title-wrapper">
                <text class="deliver-detail__module-title">工单详情</text>
                <image
                  v-if="state.info.urgency === 2"
                  class="deliver-detail__icon"
                  :src="IMG_ICON_SPEED"
                />
                <view v-if="state.info.urgency === 3" class="deliver-detail__icon-wrapper">
                  <image class="deliver-detail__icon" :src="IMG_ICON_SPEED" />
                  <image class="deliver-detail__icon" :src="IMG_ICON_SPEED" />
                </view>
                &nbsp;
                <text
                  class="deliver-detail__remain-time"
                  v-if="params.from === 'default' && state.info.status !== 'deliver_task_complete'"
                  >剩{{ formatSeconds(state.info.validDuration || 0) }}</text
                >
              </view>
            </template>
            <template v-slot:link>
              <view>
                <text
                  class="deliver-detail__status"
                  :style="{
                    color: state.info.status
                      ? DELIVER_ORDER_STATUS_COLOR[state.info.status]
                      : '#999',
                    backgroundColor: state.info.status
                      ? DELIVER_ORDER_STATUS_BG_COLOR[state.info.status]
                      : '#999',
                  }"
                >
                  {{ state.info.status ? DELIVER_ORDER_STATUS[state.info.status] : '-' }}
                </text>
              </view>
            </template>
          </nut-cell>
          <nut-cell title="工单号" :desc="state.info.orderCode || '-'" />
          <nut-cell
            title="提单人"
            :desc="`${state.info.releaseUserName}(${state.info.releaseUserPhone})` || '-'"
          />
          <nut-cell
            title="运送类型"
            :desc="`${state.info.orderTypeName || '-'} - ${state.info.orderSubTypeName || '-'}`"
          />
          <nut-cell
            title="运送路线"
            :desc="`${state.info.areaNameStart || '-'} 至 ${state.info.areaNameEnd || '-'}`"
          />
          <nut-cell title="计划时间" :desc="planTime" />
          <nut-cell title="运送工具" :desc="state.info.deliverToolName || '-'" />
          <nut-cell title="患者信息" :desc="state.info.patientInfo || '-'" />
          <nut-cell title="工单描述" :desc="state.info.description || '-'" />
          <nut-cell v-if="imgList && imgList.length">
            <app-upload-image :default-image-list="imgList" :readonly="true" height="120px" />
          </nut-cell>
        </nut-cell-group>
        <nut-cell-group>
          <nut-cell>
            <template v-slot:title>
              <text class="deliver-detail__module-title">工单轨迹</text>
            </template>
          </nut-cell>
          <nut-cell>
            <app-deliver-event-list :list="state.info.woDeliverEventDto" />
          </nut-cell>
        </nut-cell-group>

        <nut-cell-group v-if="state.endTaskEventItem && state.endTaskEventItem.id">
          <nut-cell>
            <template v-slot:title>
              <text class="deliver-detail__module-title">处理结果</text>
            </template>
          </nut-cell>
          <nut-cell>
            <template v-slot:title>
              <text>情况描述</text>
              <nut-textarea
                placeholder="请输入情况说明"
                rows="8"
                limit-show
                text-align="left"
                readonly
                max-length="200"
                v-model="state.endTaskEventItem.opinion"
              />
            </template>
          </nut-cell>
          <nut-cell v-if="imgList4EndTaskEvent && imgList4EndTaskEvent.length">
            <template v-slot:title>
              <text>上传图片</text>
              <nut-cell>
                <app-upload-image :default-image-list="imgList4EndTaskEvent" readonly />
              </nut-cell>
            </template>
          </nut-cell>
        </nut-cell-group>

        <nut-cell-group
          v-if="state.info.status === 'deliver_task_complete' && state.info.evaluateTask === 1"
        >
          <nut-cell>
            <template v-slot:title>
              <text class="deliver-detail__module-title">工单评价</text>
            </template>
          </nut-cell>
          <nut-cell title="服务时间">
            <template v-slot:link>
              <nut-rate
                v-model="evaluateTaskFormState.woDeliverEventDto.starNumber"
                readonly
                active-color="#ffc800"
              />
            </template>
          </nut-cell>
          <nut-cell title="服务质量">
            <template v-slot:link>
              <nut-rate
                v-model="evaluateTaskFormState.woDeliverEventDto.starNumberQuality"
                readonly
                active-color="#ffc800"
              />
            </template>
          </nut-cell>
          <nut-cell title="评价内容">
            <template v-slot:link>
              <text>
                {{ evaluateTaskFormState.woDeliverEventDto.opinion || '-' }}
              </text>
            </template>
          </nut-cell>
        </nut-cell-group>

        <nut-cell-group
          v-else-if="
            state.info.status === 'deliver_task_complete' &&
            state.info.evaluateTask === 2 &&
            params.from === 'report-history'
          "
        >
          <nut-cell>
            <template v-slot:title>
              <text class="deliver-detail__module-title">工单评价</text>
            </template>
          </nut-cell>
          <nut-cell title="服务时间">
            <template v-slot:link>
              <nut-rate
                v-model="evaluateTaskFormState.woDeliverEventDto.starNumber"
                active-color="#ffc800"
              />
            </template>
          </nut-cell>
          <nut-cell title="服务质量">
            <template v-slot:link>
              <nut-rate
                v-model="evaluateTaskFormState.woDeliverEventDto.starNumberQuality"
                active-color="#ffc800"
              />
            </template>
          </nut-cell>
          <nut-cell title="评价内容">
            <template v-slot:link>
              <nut-textarea
                class="deliver-detail__evaluate-task-textarea"
                v-model="evaluateTaskFormState.woDeliverEventDto.opinion"
                limit-show
                rows="5"
                max-length="50"
              />
            </template>
          </nut-cell>
        </nut-cell-group>
      </view>
    </scroll-view>

    <view
      v-if="
        state.info.status === 'deliver_task_complete' &&
        state.info.evaluateTask === 2 &&
        params.from === 'report-history'
      "
      class="deliver-detail__footer"
    >
      <nut-button
        class="deliver-detail__footer-btn"
        shape="round"
        type="info"
        @click="evaluateTask"
      >
        提交评价
      </nut-button>
    </view>

    <view v-if="params.from === 'default'">
      <view
        v-if="state.info.status === 'deliver_task_assign' && state.info.assignModel === 3"
        class="deliver-detail__footer"
      >
        <nut-button
          class="deliver-detail__footer-btn"
          shape="round"
          type="info"
          @click="rushAppTask"
        >
          抢单
        </nut-button>
      </view>
      <view v-if="state.info.status === 'deliver_task_receive'" class="deliver-detail__footer">
        <nut-button
          class="deliver-detail__footer-btn"
          shape="round"
          type="info"
          @click="receiveAppTask"
        >
          接单
        </nut-button>
        <nut-button
          class="deliver-detail__footer-btn"
          shape="round"
          type="danger"
          @click="backAppTask"
        >
          回退
        </nut-button>
      </view>
      <view v-else-if="state.info.status === 'deliver_task_start'" class="deliver-detail__footer">
        <nut-button
          class="deliver-detail__footer-btn"
          shape="round"
          type="info"
          @click="startAppTaskScan"
        >
          扫码开始运送
        </nut-button>
      </view>
      <view v-else-if="state.info.status === 'deliver_task_end'" class="deliver-detail__footer">
        <nut-button
          class="deliver-detail__footer-btn"
          shape="round"
          type="warning"
          @click="
            navigateTo({
              url: `/pages/deliver/process/index?id=${params.id}`,
            })
          "
        >
          完成运送
        </nut-button>
      </view>
      <view v-else-if="state.info.status === 'deliver_task_confirm'" class="deliver-detail__footer">
        <nut-button
          class="deliver-detail__footer-btn"
          shape="round"
          type="warning"
          @click="
            navigateTo({
              url: `/pages/deliver/sign/index?id=${params.id}`,
            })
          "
        >
          签字确认
        </nut-button>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
